package com.leo;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.PixelReader;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

import java.io.File;
import java.io.FileWriter;

/**
 * @ClassName ImageToTxt
 * @Description 将图片保存到txt文本
 * @Author wangss
 * @date 2020.06.02 22:48
 * @Version 1.0
 */
public class ImageToTxt extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        AnchorPane an = new AnchorPane();
        an.setStyle("-fx-background-color: #e7eeea");
        Scene scene = new Scene(an);

        Image image = new Image("images/花木兰.jpg", 300, 200, false, true);
        PixelReader pixelReader = image.getPixelReader();

        ImageView imageView = new ImageView(image);

        an.getChildren().add(imageView);
        primaryStage.setScene(scene);
        primaryStage.setTitle("ImageViewDemo");
        primaryStage.setWidth(600d);
        primaryStage.setHeight(600d);
        primaryStage.setResizable(false);
        primaryStage.show();

        String[] data = {"#", "#", "#", "m", "w", "n", "s", "k", "$", "g", "a", "c", "v", "u", "o", "?", ";", "+", "=", "-", ",", ".", " ", " ", " ", " "};
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < image.getHeight(); i++) {
            for (int j = 0; j < image.getWidth(); j++) {
                Color color = pixelReader.getColor(j, i);
                int value = (int) (color.getRed() * 255);
                int index = Math.round(value / 10);
                sb.append(data[index]);
            }
            sb.append("\r\n");
        }

        // 写入文件
        File file = new File("D:/log/new.txt");
        FileWriter fw = new FileWriter(file);
        fw.write("");
        fw.write(sb.toString());
        fw.flush();
        fw.close();
    }
}
